<?php

	$code = $_REQUEST['code'];
	$openid = $_REQUEST['openid'];
	$token = $_REQUEST['token'];
 
	$AppID = 'wx3998553b3b43b1f0';
	$AppSecret = '37912d3dd06fb16f804e143df9f0e79d';
	// $AppID = 'wxa8b4550d6596cc69';
	// $AppSecret = '6fd24da4953eb0793ec4e962790b0402';

	if($code){
		$url = sprintf('https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',$AppID,$AppSecret,$code);
		$tmp = file_get_contents($url);
		if(!$tmp) {
			$re = array('ret'=>1,'msg'=>'get userinfo error'); 
file_put_contents('log',$code.'===post==='.json_encode($re) . "\n\n",FILE_APPEND);
		}
		
		$access_token = json_decode($tmp,true);	
		if(isset($access_token['errcode'])){
file_put_contents('log',$code.'===post==='.json_encode($access_token) . "\n\n",FILE_APPEND);
		}
		
		
		$refresh_url = sprintf("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s",$AppID, $access_token['refresh_token']); 
		$refresh = file_get_contents($refresh_url);
		if(!$refresh) {
			$re = array('ret'=>1,'msg'=>'get userinfo error');
file_put_contents('log',$code.'==access_token=='.json_encode($access_token).'=post==='.json_encode($re) . "\n\n",FILE_APPEND);
		}
		
		$token_rs = json_decode($refresh,true);	
		if(isset($token_rs['errcode'])){
file_put_contents('log',$code.'==token_rs=='.json_encode($token_rs) . "\n\n",FILE_APPEND);

		}

		$openid = $token_rs['openid'];
		$token = $token_rs['access_token'];
	} 
	
	$userinfo_url = sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s",$token,$openid);
	
	$tmp_info = file_get_contents($userinfo_url);
//file_put_contents('log',$userinfo_url.'post==='.json_encode($tmp_info) . "\n\n",FILE_APPEND);

	if(!$tmp_info) {
		$re = array('ret'=>2,'msg'=>'get userinfo error');
		die(json_encode($re));
	}
	$userinfo = json_decode($tmp_info,true);
	
	$re = array(
		'ret' => 0,
		'msg' => 'success',
		'info'=> $userinfo,
		'expires_time' => time() + 86400 * 7,
		'password' => $openid,
	);
	
	echo json_encode($re);
